package com.batchengine.worker;

import com.batchengine.pool.ExecutorWorkerPool;
import com.batchengine.pool.ProducerConsumerWorkerPool;
import com.batchengine.pool.WorkerPool;
import static com.batchengine.schedular.CronSchedularWorkerManager.getCronSchedular;
import com.batchengine.task.TaskContext;
import static com.batchengine.util.LoggingFactory.createLogger;
import static com.batchengine.worker.Status.FINISHED;
import org.apache.log4j.Logger;

/**
 * Created by  solutions
 * Author: sunil.incubator@yahoo.com
 * Date: Jul 29, 2009
 */
public class PCStopSignal extends StopSignal {

    private static final Logger logger = createLogger();

    private Worker dataGatherer;

    public PCStopSignal(String name, long taskId, WorkerPool pool, Worker dataGatherer) {
        super(name, taskId, pool);
        this.dataGatherer = dataGatherer;
    }

    /**
     * this will be called only after the scheduled task finishes its work
     *
     * @param context, the context
     */
//TODO     remove the cron tash from the scheduled task list
    public void stopSignal(TaskContext context) {

        ScheduledTask scheduledTask = getCronSchedular().getScheduledTask(getJobId());
        if (null == scheduledTask) {
            return;
        }
        if (null == getPool()) {
            scheduledTask.setStatus(FINISHED);
            return;
        }

        WorkerPool workerPool = scheduledTask.getWorkerPool();
        if (null == workerPool || workerPool instanceof ExecutorWorkerPool) {
            return;
        }

        boolean gathererDead = false;
        while (!gathererDead) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                logger.error("error@PCStopSignal#stopSignal", e);
            }
            gathererDead = FINISHED.equals(((ProducerConsumerWorkerPool) workerPool).getDataGatherer().getStatus());
        }
        removeWorkersFromPool(context);
        scheduledTask.setStatus(FINISHED);
    }

    public Worker getDataGatherer() {
        return dataGatherer;
    }
}
